# -*- coding: utf-8 -*-
"""
Created on Fri May 26 20:38:53 2017

@author: claude
"""
import re
#import pymongo
from pymongo import MongoClient

class MongoDBClient():
    def __init__(self):
        self.client = MongoClient('localhost', 27017)
        self.db = self.client.xiaohongshu
        
class QueryItems():
    collection_searched = 'searched'
    collection_item = 'items'
    def __init__(self):
        self.db = MongoDBClient().db
    def query_searched(self, keyword):
        return self.db[self.collection_searched].find_one({"keyword": keyword})
    def query_items_by_id(self, _id):
        return self.db[self.collection_item].find_one({"_id": _id})
    def query_items_by_keyword(self, keyword):
        pattern = re.compile(".*"+keyword+".*")
        return self.db[self.collection_item].find({"$or": [{"product":pattern}, {"title":pattern }]})


def jaccard_similarity(x,y):
    """ 
    returns the jaccard similarity between two lists 
    """
    intersection_cardinality = len(set.intersection(*[set(x), set(y)]))
    union_cardinality = len(set.union(*[set(x), set(y)]))
    return intersection_cardinality/float(union_cardinality)
        
def get_jaccard_similarity_matrix(temp_dict):
    res = []
    for item_1 in temp_dict.values():
        rows = []
        for item_2 in temp_dict.values():
            if len(item_1)+len(item_2)==0:
                rows.append(0.0)
            else:
                rows.append(jaccard_similarity(item_1, item_2))
        res.append(rows) 
    return res
    
if __name__=="__main__":
    queryitem = QueryItems()
    searched = queryitem.query_searched("rafa")
    temp_dict = {}
    for item_idx in searched['ids']:
        item = queryitem.query_items_by_id(item_idx)
        temp_dict[item['_id']] = item['related_note']
    res = get_jaccard_similarity_matrix(temp_dict)
    for x in res:
        for xx in x:
            print "%.2f\t" % xx,
        print ""
#    cursor = queryitem.query_items_by_keyword("rafa")
#    for item in cursor:
#        print item